
#include "permutations.h"

void swap(int * lh, int * rh) {
  int t = *lh;
  *lh = *rh;
  *rh = t;
}

void bubbleSort(int *ary, int size) {
  int pass, j;
  for (pass = 1; pass < size; ++pass)
    for (j = 0; j < size - 1; ++j)
      if (ary[j] > ary[j + 1]) {
	int t;
	t = ary[j];
	ary[j] = ary[j+1];
	ary[j+1] = t;
  //	swap(&array[j], &array[j + 1]);  
      }
}

int permutation_next(int *array, int length) {
  int len = length - 1;
  int replace = len;
  int current;
  int size;
  int * ary;
  int pass, j;
  int t;
  while (--replace != -1) { 
    for (current = len; current != replace; --current) { 
      if (array[current] > array[replace]) {

	ary = &array[replace + 1];
	size = len-replace;
	//	swap(&array[current], &array[replace]);
	t = array[current];
	array[current] = array[replace];
	array[replace] = t;
	for (pass = 1; pass < size; ++pass)
	  for (j = 0; j < size - 1; ++j)
	    if (ary[j] > ary[j + 1]) {
	      t = ary[j];
	      ary[j] = ary[j+1];
	      ary[j+1] = t;
	      //	swap(&array[j], &array[j + 1]);  
	    }
	//	bubbleSort(&array[replace + 1], len - replace);
	return 1;
      }
    }
  }
  ary = array;
  size = length;
  for (pass = 1; pass < size; ++pass)
    for (j = 0; j < size - 1; ++j)
      if (ary[j] > ary[j + 1]) {
	t = ary[j];
	ary[j] = ary[j+1];
	ary[j+1] = t;
	//	swap(&array[j], &array[j + 1]);  
      }
  return 0;
}
